package com.mtt.erp.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mtt.erp.common.domain.MttErpConstant;
import com.mtt.erp.common.domain.QueryRequest;
import com.mtt.erp.common.domain.Tree;
import com.mtt.erp.common.utils.SortUtil;
import com.mtt.erp.common.utils.TreeUtil;
import com.mtt.erp.common.utils.UUIDUtils;
import com.mtt.erp.goods.domain.TCategory;
import com.mtt.erp.goods.dao.TCategoryMapper;
import com.mtt.erp.goods.dto.TCategoryCreateDto;
import com.mtt.erp.goods.dto.TCategoryDto;
import com.mtt.erp.goods.dto.TCategoryUpdateDto;
import com.mtt.erp.goods.service.ITCategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mtt.erp.goods.vo.TCategoryTreeVo;
import com.mtt.erp.goods.vo.TCategoryVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @Description: 分类表ServiceImpl
 * @Author: guomengzhou
 * @CreateDate: 2019/6/4 14:28
 * @Version: 1.0
 */
@Slf4j
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class TCategoryServiceImpl extends ServiceImpl<TCategoryMapper, TCategory> implements ITCategoryService {
    @Value("${erp.max.batch.insert.num}")
    private int batchInsertMaxNum;
    /**
     * 分类列表
     *
     * @param request
     * @param tCategoryDto
     * @return
     */
    @Override
    public TCategoryTreeVo findCategory(QueryRequest request, TCategoryDto tCategoryDto) {
        TCategoryTreeVo tCategoryVo = TCategoryTreeVo.builder().build();
        try {
            List<TCategory> categorys = findCategory(tCategoryDto, request);
            List<Tree<TCategory>> trees = new ArrayList<>();
            buildTrees(trees, categorys);
            Tree<TCategory> categoryTree = TreeUtil.build(trees);

            tCategoryVo.setTotal(categorys.size());
            tCategoryVo.setTree(categoryTree);

        } catch (Exception e) {
            log.error("获取分类列表失败", e);
            tCategoryVo.setTree(null);
            tCategoryVo.setTotal(0);
        }
        return tCategoryVo;
    }

    /**
     * 获取所有分类
     *
     * @param tCategoryDto,request
     * @return
     */
   @Override
    public List<TCategory> findCategory(TCategoryDto tCategoryDto,QueryRequest request) {
       QueryWrapper<TCategory> queryWrapper = new QueryWrapper<>();
       if (StringUtils.isNotBlank(tCategoryDto.getName()))
           queryWrapper.lambda().eq(TCategory::getName, tCategoryDto.getName());
       SortUtil.handleWrapperSort(request, queryWrapper, "sort", MttErpConstant.ORDER_ASC, true);
       return this.baseMapper.selectList(queryWrapper);
    }

    /**
     * 新建类别
     *
     * @param tCategoryCreateDto
     */
    @Override
    @Transactional
    public void createCategory(TCategoryCreateDto tCategoryCreateDto) {
        TCategory tCategory = TCategory.builder().build();
        BeanUtils.copyProperties(tCategoryCreateDto,tCategory);
        tCategory.setId(UUIDUtils.getUUID());//生成唯一主键
        if(StringUtils.isBlank(tCategory.getParentId())){
            tCategory.setParentId(TCategory.topCategoryParentId);
        }
        this.save(tCategory);
    }

    /**
     * 修改类别
     *
     * @param tCategoryUpdateDto
     */
    @Override
    @Transactional
    public void updateCategory(TCategoryUpdateDto tCategoryUpdateDto) {
        TCategory tCategory = TCategory.builder().build();
        BeanUtils.copyProperties(tCategoryUpdateDto,tCategory);
        this.updateById(tCategory);
    }

    /**
     * 删除类别
     *
     * @param categoryIds
     */
    @Override
    @Transactional
    public void deleteCategory(String[] categoryIds) throws Exception {
        Arrays.stream(categoryIds).forEach(categoryId -> this.baseMapper.deleteCategory(categoryId));
    }

    /**
     * 通过id查询
     *
     * @param id
     */
    @Override
    public TCategoryVo findCategoryById(String id) {
        TCategory tcategory = this.getById(id);
        TCategoryVo tCategoryVo = TCategoryVo.builder().build();
        if(tcategory != null){
            BeanUtils.copyProperties(tcategory,tCategoryVo);
        }else{
            return null;
        }
        return tCategoryVo;
    }


    /**
   * 将分类画成树
   * @author      guomengzhou
   * @param
   * @return
   * @date        2019/6/4 15:17
   */
    private void buildTrees(List<Tree<TCategory>> trees, List<TCategory> tCategorys) {
        tCategorys.forEach(tCategory -> {
            Tree<TCategory> tree = new Tree<>();
            tree.setId(tCategory.getId());
            tree.setKey(tree.getId());
            tree.setParentId(tCategory.getParentId());
            tree.setText(tCategory.getName());
            tree.setOrder(tCategory.getSort());
            tree.setTitle(tree.getText());
            tree.setValue(tree.getId());
            tree.setCode(tCategory.getCode());
            trees.add(tree);
        });
    }
}
